<template>
    <view class="content">
        <show-modal></show-modal>
        <!-- <navigation-custom :config="config" /> -->

        <view class="search-box">
            <!-- mSearch组件 如果使用原样式，删除组件元素-->
            <!-- <mSearch class="mSearch-input-box" :mode="2" button="inside" :placeholder="defaultKeyword" @search="doSearch(false)"
			 @input="inputChange" @confirm="doSearch(false)" v-model="keyword"></mSearch> -->

            <!-- 原样式 如果使用原样式，恢复下方注销代码 -->
            <view class="input-box">
                <input type="text" :placeholder="defaultKeyword" @input="inputChange" v-model="keyword"
                    @confirm="doSearch(false)" placeholder-class="placeholder-class" confirm-type="search">
            </view>
            <view class="search-btn" @tap="doSearch(false)">搜索</view>
            <!-- 原样式 end -->
        </view>

        <view class="search-keyword" @touchstart="blur">
            <scroll-view class="keyword-list-box" v-show="isShowKeywordList  && !isShowWaterfall" scroll-y>
                <view class="keyword-entry" hover-class="keyword-entry-tap" v-for="row in keywordList"
                    :key="row.keyword">
                    <view class="keyword-text" @tap="doSearch(row.keyword)">
                        <rich-text :nodes="row.htmlStr"></rich-text>
                    </view>
                    <view class="keyword-img" @tap="setkeyword(row)">
                        <image src="/static/icon/check1.png"></image>
                    </view>
                </view>
            </scroll-view>
            <scroll-view class="keyword-box" v-show="!isShowKeywordList && !isShowWaterfall" scroll-y>
                <view class="keyword-block" v-if="oldKeywordList.length>0">
                    <view class="keyword-list-header">
                        <view>历史搜索</view>
                        <view>
                            <image @tap="oldDelete" src="/static/icon/delete.png"></image>
                        </view>
                    </view>
                    <view class="keyword">
                        <view v-for="(keyword,index) in oldKeywordList" @tap="doSearch(keyword)" :key="index">
                            {{keyword}}
                        </view>
                    </view>
                </view>
                <view class="keyword-block">
                    <view class="keyword-list-header">
                        <view>热门搜索</view>
                        <view>
                            <image @tap="hotToggle" :src="'/static/icon/attention'+forbid+'.png'"></image>
                        </view>
                    </view>
                    <view class="keyword" v-if="forbid==''">
                        <view v-for="(keyword,index) in hotKeywordList" @tap="doSearch(keyword)" :key="index">
                            {{keyword}}
                        </view>
                    </view>
                    <view class="hide-hot-tis" v-else>
                        <view>当前搜热门搜索已隐藏</view>
                    </view>
                </view>
            </scroll-view>

            <waterfall-flow :list="list" v-show="isShowWaterfall" :loading="loading" @click="choose"></waterfall-flow>
        </view>

    </view>
</template>

<script>
    // //引用 mSearch组件，如不需要删除即可
    // import mSearch from '@/components/mehaotian-search-revision/mehaotian-search-revision.vue';
    export default {
        data() {
            return {
                defaultKeyword: "",
                keyword: "",
                oldKeywordList: [],
                hotKeywordList: [],
                keywordList: [],
                forbid: '',
                isShowKeywordList: false,

                // 导航栏
                config: {
                    title: "搜索", //title
                    bgcolor: "#c1a379", //背景颜色
                    type: 1, //type 1，3胶囊 2，4无胶囊模式
                    linear: true, //是为开启下滑渐变
                },

                // 瀑布流配置
                isShowWaterfall: false,
                page: 1,
                total: 1,
                list: [], // 列表
                loading: true,
            }
        },
        onLoad() {
            this.init();
        },
        methods: {
            init() {
                this.page = 1;
                this.loadDefaultKeyword();
                this.loadOldKeyword();
                this.loadHotKeyword();
            },
            blur() {
                uni.hideKeyboard()
            },
            //加载默认搜索关键字
            loadDefaultKeyword() {
                //定义默认搜索关键字，可以自己实现ajax请求数据再赋值
                //用户未输入时，以水印方式显示在输入框，直接不输入内容搜索会搜索默认关键字
                this.defaultKeyword = "默认关键字";
            },
            //加载历史搜索，自动读取本地Storage
            loadOldKeyword() {
                uni.getStorage({
                    key: 'OldKeys',
                    success: (res) => {
                        var OldKeys = JSON.parse(res.data);
                        this.oldKeywordList = OldKeys;
                    }
                });
            },
            //加载热门搜索
            loadHotKeyword() {
                //定义热门搜索关键字，可以自己实现ajax请求数据再赋值
                this.hotKeywordList = ['6月龄', '8月龄', '10月龄', '12月龄', '泥糊', '营养', '维生素', '炖煮', '蛋黄奶豆'];
            },
            //监听输入
            inputChange(event) {
                //兼容引入组件时传入参数情况
                var keyword = event.detail ? event.detail.value : event;
                if (!keyword) {
                    this.keywordList = [];
                    this.isShowKeywordList = false;
                    this.isShowWaterfall = false;
                    return;
                }
                this.isShowKeywordList = true;
                //以下示例截取淘宝的关键字，请替换成你的接口
                this.$api.http.request({
                    url: 'v1/bookFrontend/suggest?keyword=' + keyword,
                    method: 'GET',
                }).then((res) => {
                    if (res.data.length > 0) {
                        this.keywordList = this.drawCorrelativeKeyword(res.data, keyword);
                    } else {
                        this.isShowKeywordList = false;
                    }
                }).catch((err) => {
                    console.error('request fail', err);
                })
            },
            //高亮关键字
            drawCorrelativeKeyword(keywords, keyword) {
                var len = keywords.length,
                    keywordArr = [];
                for (var i = 0; i < len; i++) {
                    var row = keywords[i];
                    //定义高亮 #9f9f9f
                    var html = row.replace(keyword, "<span style='color: #9f9f9f;'>" + keyword + "</span>");
                    html = '<div>' + html + '</div>';
                    var tmpObj = {
                        keyword: row,
                        htmlStr: html
                    };
                    keywordArr.push(tmpObj)
                }
                return keywordArr;
            },
            //顶置关键字
            setkeyword(data) {
                this.keyword = data.keyword;
            },
            //清除历史搜索
            oldDelete() {
                this.$showModal({
                    content: '确定清除历史搜索记录？',
                    success: (res) => {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            this.oldKeywordList = [];
                            uni.removeStorage({
                                key: 'OldKeys'
                            });
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                });
            },
            //热门搜索开关
            hotToggle() {
                this.forbid = this.forbid ? '' : '_forbid';
            },
            //执行搜索
            doSearch(key) {
                key = key ? key : this.keyword ? this.keyword : this.defaultKeyword;
                this.keyword = key;
                this.saveKeyword(key); //保存为历史 
                this.keywordList = []; //清除检索列表
                this.list = []; // 清除检索结果
                this.page = 1;
                this.getList(); // 瀑布流加载结果
            },
            // 瀑布流 模拟加载数据
            getList() {
                this.loading = true;
                setTimeout(() => {
                    this.loading = true
                    let data = {
                        "currPage": this.page,
                        "pageSize": 10,
                        "entity": {
                            "searchKeyword": this.keyword
                        }
                    }
                    this.$api.searchBook(data).then((res) => {
                        // 延迟 120 毫秒隐藏加载动画，为了跟组件里面的 100 毫秒定位有个平缓过度
                        setTimeout(() => {
                            this.loading = false;
                        }, 120);

                        this.total = res.data.totalCount;
                        if (res.data.records != null) {
                            this.list = this.list.concat(res.data.records);
                            this.isShowWaterfall = true;
                        } 
                        
                        if (res.data.totalCount == 0) {
                            this.isShowWaterfall = false;
                            uni.showToast({
                                title: "暂无更多数据",
                                icon: "none"
                            })
                        }
                    }).catch((err) => {
                        // 延迟 120 毫秒隐藏加载动画，为了跟组件里面的 100 毫秒定位有个平缓过度
                        setTimeout(() => {
                            this.loading = false;
                        }, 120);
                        console.error('request fail', err);
                    })
                }, 500)
            },
            // 瀑布流 选中
            choose(item) {
                // item 返回选中 JSON 对象
                console.log(item)
                uni.navigateTo({
                    url: "/pages/home/detail?id=" + item.id
                })
            },
            reachBottom() {
                console.log('home-search onReachBottom')
                if (!this.keyword) {
                    console.log("keywork is empty!", this.page);
                    return;
                }

                if (this.loading) return
                
                this.page++;
                this.loading = true;
                this.getList();
            },
            //保存关键字到历史记录
            saveKeyword(keyword) {
                uni.getStorage({
                    key: 'OldKeys',
                    success: (res) => {
                        console.log(res.data);
                        var OldKeys = JSON.parse(res.data);
                        var findIndex = OldKeys.indexOf(keyword);
                        if (findIndex == -1) {
                            OldKeys.unshift(keyword);
                        } else {
                            OldKeys.splice(findIndex, 1);
                            OldKeys.unshift(keyword);
                        }
                        //最多10个纪录
                        OldKeys.length > 10 && OldKeys.pop();
                        uni.setStorage({
                            key: 'OldKeys',
                            data: JSON.stringify(OldKeys)
                        });
                        this.oldKeywordList = OldKeys; //更新历史搜索
                    },
                    fail: (e) => {
                        var OldKeys = [keyword];
                        uni.setStorage({
                            key: 'OldKeys',
                            data: JSON.stringify(OldKeys)
                        });
                        this.oldKeywordList = OldKeys; //更新历史搜索
                    }
                });
            }
        },
        onReachBottom() {
            console.log('search-home onReachBottom')
            this.reachBottom();
        }
    }
</script>
<style>
    view {
        display: block;
    }

    .search-box {
        width: 95%;
        background-color: rgb(242, 242, 242);
        padding: 15upx 2.5%;
        display: flex;
        justify-content: space-between;
    }

    .search-box .mSearch-input-box {
        width: 100%;
    }

    .search-box .input-box {
        width: 85%;
        flex-shrink: 1;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .search-box .search-btn {
        width: 15%;
        margin: 0 0 0 2%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-shrink: 0;
        font-size: 28upx;
        color: #fff;
        background: linear-gradient(to right, #F7D3CE, #DA2C15);
        border-radius: 60upx;
    }

    .search-box .input-box>input {
        width: 100%;
        height: 60upx;
        font-size: 28upx;
        border: 0;
        border-radius: 60upx;
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
        padding: 0 3%;
        margin: 0;
        background-color: #ffffff;
    }

    .placeholder-class {
        color: #9e9e9e;
    }

    .search-keyword {
        width: 100%;
        background-color: rgb(242, 242, 242);
    }

    .keyword-list-box {
        height: calc(100vh - 110upx);
        padding-top: 10upx;
        border-radius: 20upx 20upx 0 0;
        background-color: #fff;
    }

    .keyword-entry-tap {
        background-color: #eee;
    }

    .keyword-entry {
        width: 94%;
        height: 80upx;
        margin: 0 3%;
        font-size: 30upx;
        color: #333;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: solid 1upx #e7e7e7;
    }

    .keyword-entry image {
        width: 60upx;
        height: 60upx;
    }

    .keyword-entry .keyword-text,
    .keyword-entry .keyword-img {
        height: 80upx;
        display: flex;
        align-items: center;
    }

    .keyword-entry .keyword-text {
        width: 90%;
    }

    .keyword-entry .keyword-img {
        width: 10%;
        justify-content: center;
    }

    .keyword-box {
        height: calc(100vh - 110upx);
        border-radius: 20upx 20upx 0 0;
        background-color: #fff;
    }

    .keyword-box .keyword-block {
        padding: 10upx 0;
    }

    .keyword-box .keyword-block .keyword-list-header {
        width: 94%;
        padding: 10upx 3%;
        font-size: 27upx;
        color: #333;
        display: flex;
        justify-content: space-between;
    }

    .keyword-box .keyword-block .keyword-list-header image {
        width: 40upx;
        height: 40upx;
    }

    .keyword-box .keyword-block .keyword {
        width: 94%;
        padding: 3px 3%;
        display: flex;
        flex-flow: wrap;
        justify-content: flex-start;
    }

    .keyword-box .keyword-block .hide-hot-tis {
        display: flex;
        justify-content: center;
        font-size: 28upx;
        color: #6b6b6b;
    }

    .keyword-box .keyword-block .keyword>view {
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 60upx;
        padding: 0 20upx;
        margin: 10upx 20upx 10upx 0;
        height: 60upx;
        font-size: 28upx;
        background-color: rgb(242, 242, 242);
        color: #6b6b6b;
    }
</style>
